package views

import (
	"errors"
	"fanqiechaodan-blog/common"
	"fanqiechaodan-blog/service"
	"go.uber.org/zap"
	"net/http"
	"strconv"
	"strings"
)

func (*HTMLApi) Category(writer http.ResponseWriter, request *http.Request) {
	category := common.Template.Category
	// 从路由上拿到参数ID
	path := request.URL.Path
	cidStr := strings.TrimPrefix(path, "/category/")
	cid, err := strconv.Atoi(cidStr)
	if err != nil {
		zap.S().Errorf("解析路由参数失败;路由:%s;err:%s", path, err.Error())
		category.WriteError(writer, errors.New("解析参数失败"))
		return
	}
	// 解析分页参数
	pageStr := request.FormValue("page")
	if pageStr == "" {
		pageStr = "1"
	}
	pageSizeStr := request.FormValue("pageSize")
	if pageSizeStr == "" {
		pageSizeStr = "10"
	}
	page, err := strconv.Atoi(pageStr)
	if err != nil {
		zap.S().Errorf("解析page参数失败;原因:%s", err.Error())
		category.WriteError(writer, errors.New("解析参数失败"))
		return
	}
	pageSize, err := strconv.Atoi(pageSizeStr)
	if err != nil {
		zap.S().Errorf("解析pageSizeStr参数失败;原因:%s", err.Error())
		category.WriteError(writer, errors.New("解析参数失败"))
		return
	}
	res, err := service.GetPostByCategoryId(cid, page, pageSize)
	if err != nil {
		zap.S().Errorf("根据分类id查询文章列表失败;cid:%d,page:%d,pageSize:%d,err:%s", cid, page, pageSize, err.Error())
		category.WriteError(writer, errors.New("查询失败"))
		return
	}
	category.WriteData(writer, res)
}
